<?php

class CommandLineRequest extends TinyMVCRequest {

	private $optionsWithArgs;
	private $scriptName;

	private function __construct(Array $optionsWithArgs = array()) {
		global $argv;

		$this->optionsWithArgs = $optionsWithArgs;
		$this->paramArray = $this->parseArguments($argv);
		// TODO: implement loading session data from file
		$this->sessionArray = $this->paramArray;
	}

	/**
	 * @return CommandLineRequest
	 */
	static public function getInstance(Array $optionsWithArgs = array()) {
		if(self::$instance == null) {
			self::$instance = new CommandLineRequest($optionsWithArgs);
		}
		return self::$instance;
	}

	/**
	 * parsing arguments passed to script ($argv array)
	 *
	 * This juicy bit came from Mediawiki software (http://www.mediawiki.org)
	 */
	private function parseArguments(Array $arguments) {
		$args = array();
		$options = array();

		for( $arg = reset( $arguments ); $arg !== false; $arg = next( $arguments ) ) {
			if ( $arg == '--' ) {
				# End of options, remainder should be considered arguments
				$arg = next( $arguments );
				while( $arg !== false ) {
					$args[] = $arg;
					$arg = next( $arguments );
				}
				break;
			} elseif ( substr( $arg, 0, 2 ) == '--' ) {
				# Long options
				$option = substr( $arg, 2 );
				if ( in_array( $option, $this->optionsWithArgs ) ) {
					$param = next( $arguments );
					if ( $param === false ) {
						echo "$arg needs a value after it\n";
						die( -1 );
					}
					$options[$option] = $param;
				} else {
					$bits = explode( '=', $option, 2 );
					if( count( $bits ) > 1 ) {
						$option = $bits[0];
						$param = $bits[1];
					} else {
						$param = 1;
					}
					$options[$option] = $param;
				}
			} elseif ( substr( $arg, 0, 1 ) == '-' ) {
				# Short options
				for ( $p=1; $p<strlen( $arg ); $p++ ) {
					$option = $arg{$p};
					if ( in_array( $option, $this->optionsWithArgs ) ) {
						$param = next( $arguments );
						if ( $param === false ) {
							echo "$arg needs a value after it\n";
							die( -1 );
						}
						$options[$option] = $param;
					} else {
						$options[$option] = 1;
					}
				}
			} else {
				$args[] = $arg;
			}
		}

		$this->scriptName = $args[0];
		return $options;
	}
}
